package my.mbean.web;

import my.mbean.MBeanAutoConfiguration;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Created by xnat on 17/5/5.
 */
//@WebServlet(name = AutoConfiguration.MBEAN_SERVLET_NAME, urlPatterns = "/mbean/*")
public class MBeanServlet extends HttpServlet {

    private RequestDispatcher dispatcher;
    private WebApplicationContext context;

    @Override
    public void init() throws ServletException {
        super.init();
        log("MBean Servlet init....");
        context = WebApplicationContextUtils.findWebApplicationContext(getServletContext());
        registerBean((BeanDefinitionRegistry) context.getAutowireCapableBeanFactory());
        dispatcher = context.getBean(RequestDispatcher.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        dispatcher.dispatch(req, resp);
    }

    private void registerBean(BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition(
                "mBeanAutoConfiguration",
                BeanDefinitionBuilder.genericBeanDefinition(MBeanAutoConfiguration.class)
                        .getBeanDefinition()
        );
//        registry.registerBeanDefinition(
//                "defaultPropertyVOBuilder",
//                BeanDefinitionBuilder.rootBeanDefinition(GenericPropertyVOBuilder.class)
//                        .setLazyInit(true)
//                        .getBeanDefinition()
//        );
//        registry.registerBeanDefinition(
//                "beansService",
//                BeanDefinitionBuilder.genericBeanDefinition(BeansService.class)
//                        .setLazyInit(true)
//                        .getBeanDefinition()
//        );
//        registry.registerBeanDefinition(
//                "mBeanController",
//                BeanDefinitionBuilder.genericBeanDefinition(MBeanController.class)
//                        .setLazyInit(true)
//                        .getBeanDefinition()
//        );
//        registry.registerBeanDefinition(
//                "requestDispatcher",
//                BeanDefinitionBuilder.genericBeanDefinition(RequestDispatcher.class)
//                        .setLazyInit(true)
//                        .getBeanDefinition()
//        );
    }
}
